import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/lunar_data.dart';
import '../config/api_config.dart';

class LunarService {
  // Both API URL and token are now imported from config file
  static String get apiUrl => ApiConfig.apiUrl;
  static String get apiToken => ApiConfig.apiToken;

  // 缓存键前缀
  static const String _cacheKeyPrefix = 'lunar_data_';

  Future<LunarData?> getLunarData(
      {DateTime? date, bool forceRefresh = false}) async {
    try {
      // Use current date if no date is provided
      final selectedDate = date ?? DateTime.now();

      // Format date as YYYY-MM-DD for cache key
      final dateStr = DateFormat('yyyy-MM-dd').format(selectedDate);
      final cacheKey = '$_cacheKeyPrefix$dateStr';

      // 检查缓存，除非强制刷新
      if (!forceRefresh) {
        final cachedData = await _getCachedData(cacheKey);
        if (cachedData != null) {
          return cachedData;
        }
      }

      // Format date as YYYY-MM-DD HH:MM for API
      final formattedDate = DateFormat('yyyy-MM-dd HH:mm').format(selectedDate);

      // Prepare API request with query parameters
      final uri = Uri.parse('$apiUrl?token=$apiToken&date=$formattedDate');

      // Send request to API
      final response = await http.get(uri);

      if (response.statusCode == 200) {
        // Parse response
        final Map<String, dynamic> jsonData = json.decode(response.body);

        // Check if API request was successful
        if (jsonData['code'] == 200 && jsonData['success'] == true) {
          // 获取数据
          final lunarData = LunarData.fromJson(jsonData['data']);

          // 缓存数据
          _cacheData(cacheKey, jsonData['data']);

          // Return lunar data
          return lunarData;
        } else {
          print('API Error: ${jsonData['message']}');
          return null;
        }
      } else {
        print('HTTP Error: ${response.statusCode}');
        return null;
      }
    } catch (e) {
      print('Exception: $e');
      return null;
    }
  }

  // 从缓存获取数据
  Future<LunarData?> _getCachedData(String key) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final jsonString = prefs.getString(key);

      if (jsonString != null) {
        final jsonData = json.decode(jsonString);
        return LunarData.fromJson(jsonData);
      }
      return null;
    } catch (e) {
      print('Cache read error: $e');
      return null;
    }
  }

  // 缓存数据
  Future<void> _cacheData(String key, Map<String, dynamic> data) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(key, json.encode(data));
    } catch (e) {
      print('Cache write error: $e');
    }
  }

  // 清除缓存
  Future<void> clearCache() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final keys = prefs.getKeys();

      for (final key in keys) {
        if (key.startsWith(_cacheKeyPrefix)) {
          await prefs.remove(key);
        }
      }
    } catch (e) {
      print('Cache clear error: $e');
    }
  }
}
